package ru.vboxdc;

import ru.vboxdc.domain.HostServer;
import ru.vboxdc.domain.VirtualMachine;

import java.util.*;

/**
 * User: lelon
 * Date: 16.02.2009
 * Time: 21:13:29
 */
public class ObjectPool {


    private List<HostServer> hostServerList = new ArrayList<HostServer>();

    private Integer lastMachineId = 0;


    public void addHostServer(HostServer hostServer) {
        hostServerList.add(hostServer);
        Collections.sort(hostServerList);
    }

    public HostServer getHostServer(Integer serverId) {
        for (HostServer hostServer : hostServerList) {
            if (hostServer.getId().equals(serverId)) return hostServer;
        }
        return null;
    }

    public void removeHostServer(HostServer hostServer) {
        hostServerList.remove(hostServer);
    }


    public List<HostServer> getHostServers() {
        return hostServerList;
    }


    public void addVirtualMachine(VirtualMachine virtualMachine, HostServer hostServer) {
        virtualMachine.setId(++lastMachineId);
        virtualMachine.setHostServer(hostServer);
        hostServer.addVMachine(virtualMachine);
    }

    public VirtualMachine getVirtualMachine(Integer machineId) {
        for (HostServer hostServer : hostServerList) {
            for (VirtualMachine virtualMachine : hostServer.getVirtualMachines()) {
                if (virtualMachine.getId().equals(machineId)) return virtualMachine;
            }
        }
        return null;
    }

    public void removeVirtualMachine(VirtualMachine virtualMachine) {
        virtualMachine.getHostServer().removeVirtualMachine(virtualMachine);
    }


    public List<VirtualMachine> getVirtualMachines() {
        List<VirtualMachine> allVirtualMachines = new ArrayList<VirtualMachine>();
        for (HostServer hostServer : hostServerList) {
            allVirtualMachines.addAll(hostServer.getVirtualMachines());
        }
        Collections.sort(allVirtualMachines);
        return allVirtualMachines;
    }


    //
    //
    //singleton
    private static class ObjectPoolHolder {
        private final static ObjectPool INSTANCE = new ObjectPool();
    }

    public static ObjectPool get() {
        return ObjectPoolHolder.INSTANCE;
    }
}
